<template>
  <div class="notification-bell">
    <!-- 通知铃铛图标 -->
    <el-dropdown @command="handleCommand" trigger="click">
      <div class="bell-icon">
        <el-badge :value="unreadCount" :hidden="unreadCount === 0" :max="99">
          <el-icon size="24"><Bell /></el-icon>
        </el-badge>
      </div>
      
      <template #dropdown>
        <el-dropdown-menu class="notification-dropdown">
          <!-- 下拉通知头部 -->
          <div class="dropdown-header">
            <span class="header-title">通知</span>
            <el-button text size="small" @click="goToNotificationCenter">
              查看全部
            </el-button>
          </div>

          <!-- 快速通知列表 -->
          <div class="quick-notifications">
            <div v-if="quickNotifications.length === 0" class="no-notifications">
              <el-icon><Bell /></el-icon>
              <span>暂无新通知</span>
            </div>
            
            <div v-else>
              <div v-for="notification in quickNotifications" 
                   :key="notification.id"
                   class="quick-notification-item"
                   @click="handleNotificationClick(notification)">
                
                <el-avatar :size="32" :src="notification.fromUser?.avatar">
                  {{ notification.fromUser?.username?.charAt(0) }}
                </el-avatar>
                
                <div class="notification-info">
                  <div class="notification-text">
                    <span class="username">{{ notification.fromUser?.username }}</span>
                    <span class="action">{{ getActionText(notification.type) }}</span>
                  </div>
                  <div class="notification-time">
                    {{ formatRelativeTime(notification.createTime) }}
                  </div>
                </div>
                
                <div class="notification-indicator" v-if="!notification.isRead"></div>
              </div>
            </div>
          </div>

          <!-- 下拉菜单操作 -->
          <div class="dropdown-actions">
            <el-dropdown-item command="markAllRead" :disabled="unreadCount === 0">
              全部标为已读
            </el-dropdown-item>
            <el-dropdown-item command="viewAll">
              查看所有通知
            </el-dropdown-item>
          </div>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 实时通知弹窗 -->
    <el-notification
      v-for="toast in toastNotifications"
      :key="toast.id"
      :title="toast.title"
      :message="toast.message"
      :type="toast.type"
      :duration="toast.duration"
      @close="removeToast(toast.id)"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 数据状态
const quickNotifications = ref([])
const toastNotifications = ref([])
const wsConnection = ref(null)

// 计算属性
const unreadCount = computed(() => {
  return quickNotifications.value.filter(n => !n.isRead).length
})

// 方法
const fetchQuickNotifications = async () => {
  // TODO: 获取最新的5条通知
}

const handleCommand = (command) => {
  switch (command) {
    case 'markAllRead':
      markAllAsRead()
      break
    case 'viewAll':
      goToNotificationCenter()
      break
  }
}

const handleNotificationClick = (notification) => {
  // TODO: 处理通知点击
  if (notification.targetPost) {
    router.push(`/post/${notification.targetPost.id}`)
  }
}

const goToNotificationCenter = () => {
  router.push('/notifications')
}

const markAllAsRead = () => {
  // TODO: 标记所有通知为已读
}

const getActionText = (type) => {
  const actions = {
    'like': '点赞了你的帖子',
    'comment': '评论了你的帖子',
    'reply': '回复了你的评论',
    'follow': '关注了你',
    'system': '系统通知'
  }
  return actions[type] || '有新动态'
}

const formatRelativeTime = (time) => {
  // TODO: 格式化相对时间
  return time
}

const showToastNotification = (notification) => {
  const toast = {
    id: Date.now(),
    title: notification.fromUser?.username || '系统通知',
    message: notification.content,
    type: 'info',
    duration: 4000
  }
  toastNotifications.value.push(toast)
}

const removeToast = (id) => {
  const index = toastNotifications.value.findIndex(t => t.id === id)
  if (index > -1) {
    toastNotifications.value.splice(index, 1)
  }
}

// WebSocket连接管理
const initWebSocket = () => {
  // TODO: 初始化WebSocket连接，接收实时通知
  // wsConnection.value = new WebSocket('ws://localhost:8080/notifications')
  
  // wsConnection.value.onmessage = (event) => {
  //   const notification = JSON.parse(event.data)
  //   quickNotifications.value.unshift(notification)
  //   showToastNotification(notification)
  // }
}

const closeWebSocket = () => {
  if (wsConnection.value) {
    wsConnection.value.close()
  }
}

onMounted(() => {
  fetchQuickNotifications()
  initWebSocket()
})

onUnmounted(() => {
  closeWebSocket()
})
</script>

<style scoped>
.notification-bell {
  position: relative;
}

.bell-icon {
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  height:50px;
  width: 50px;
  transform: translateY(7px);
}

.bell-icon:hover {
  background: rgba(102, 126, 234, 0.1);
  transform: translateY(-1px);
}

.notification-dropdown {
  width: 350px;
  max-height: 500px;
  overflow-y: auto;
}

.dropdown-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.header-title {
  font-weight: 600;
  font-size: 16px;
}

.quick-notifications {
  max-height: 300px;
  overflow-y: auto;
}

.no-notifications {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 20px;
  color: #909399;
}

.quick-notification-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  transition: background 0.3s;
  position: relative;
}

.quick-notification-item:hover {
  background: #f5f7fa;
}

.notification-info {
  flex: 1;
  min-width: 0;
}

.notification-text {
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 4px;
}

.username {
  font-weight: 600;
  color: #409eff;
  margin-right: 4px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-indicator {
  width: 8px;
  height: 8px;
  background: #409eff;
  border-radius: 50%;
  margin-left: 8px;
  flex-shrink: 0;
}

.dropdown-actions {
  border-top: 1px solid #f0f0f0;
}
</style>